<script lang="ts" setup>
import { cancelOrder, getCarOrdersList } from '@/api/car';
import { cancelUnpaidOrder, getOrdersList } from '@/api/orders';
import { CarOrderStatus, OrderStatus } from '@/constants/orders';
import { useRouter } from '@/router';
import { Order } from '@/types/order';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { reactive, ref, watch } from 'vue';
import {
  cancelOrder as cancelRestaurantOrder,
  getOrders as getRestaurantOrders
} from '../../api/restaurant-booking';
import { Order as CarOrder } from '../../types/carOrder';
import CarOrderCard from './components/car-order-card.vue';
import OrderCard from './components/order-card.vue';
import OrderTabs from './components/order-tabs.vue';
import OrderType from './components/order-type.vue';
import RestaurantOrderCard from './components/restaurant-order-card.vue';
import { useAuthStore } from '@/store/auth';
import { useLocale } from '@/locale/locale';
import { cancelOrder as cancelSpaOrder, getOrders as getSpaOrders } from '@/api/spa';
import type { ISpaOrder } from '@/types/spaOrder';
import SpaOrderCard from './components/spa-order-card.vue';
import { isWechat } from '@/utils/platform';

const { t } = useLocale();
const authStore = useAuthStore();
const scrollTop = ref(0);
const oldScrollTop = ref(0);
const statusBarH = ref(0);
const triggered = ref(false);
const currentTab = ref('checkout');
const router = useRouter();
const current = ref(0);
const items = ref<Order[]>([]);
const carItems = ref<CarOrder[]>([]);
const spaItems = ref<ISpaOrder[]>([]);

const totalCount = ref(0);
const pagination = reactive({
  pageNum: 1,
  pageSize: 10
});

// 餐厅订单
type RestaurantResult = Awaited<ReturnType<typeof getRestaurantOrders>>['data'];
type RestaurantOrders = RestaurantResult['list']['data'];
const restaurantItems = ref<RestaurantOrders>([]);

function scrollStart(e: any) {
  oldScrollTop.value = e.detail.scrollTop;
}

function fetchHotelData() {
  const payload: any = {
    pageNum: pagination.pageNum,
    pageSize: pagination.pageSize
  };
  if (current.value == 1) {
    payload['orderStatus'] = OrderStatus.WAIT_PAY;
  } else if (current.value == 2) {
    payload['orderStatus'] = OrderStatus.HAVE_PAID;
  } else if (current.value == 3) {
    payload['orderStatus'] = OrderStatus.CANCEL;
  }
  getOrdersList(payload).then((res) => {
    if (!initialized.value) {
      initialized.value = true;
    }
    if (res.code === 0) {
      totalCount.value = res.data.count;
      if (pagination.pageNum === 1) {
        items.value = res.data.List;
        triggered.value = false;
      } else if (res.data?.List) {
        items.value.push(...res.data.List);
      }
    }
  });
}

function fetchRestaurantData() {
  let orderStatus = '';
  if (current.value == 1) {
    orderStatus = OrderStatus.WAIT_PAY;
  } else if (current.value == 2) {
    orderStatus = OrderStatus.HAVE_PAID;
  } else if (current.value == 3) {
    orderStatus = OrderStatus.CANCEL;
  }
  getRestaurantOrders(pagination.pageNum, pagination.pageSize, orderStatus).then((res) => {
    if (!initialized.value) {
      initialized.value = true;
    }
    if (res.code === 0) {
      totalCount.value = res.data.list.total;
      if (pagination.pageNum === 1) {
        restaurantItems.value = [];
        setTimeout(() => {
          restaurantItems.value = res.data.list.data;
          triggered.value = false;
        }, 100);
      } else if (res.data.list.current_page != res.data.list.last_page) {
        restaurantItems.value.push(...res.data.list.data);
      }
    }
  });
}

function fetchCarData() {
  const payload: any = {
    page: pagination.pageNum,
    pageSize: pagination.pageSize
  };
  if (current.value == 1) {
    payload['orderStatus'] = CarOrderStatus.WAIT_PAY;
  } else if (current.value == 2) {
    payload['orderStatus'] = CarOrderStatus.ORDER_SUCCESS;
  } else if (current.value == 3) {
    payload['orderStatus'] = CarOrderStatus.CANCEL;
  }
  getCarOrdersList(payload).then((res) => {
    if (!initialized.value) {
      initialized.value = true;
    }
    if (res.code === 0) {
      totalCount.value = res.data.list.total;
      if (pagination.pageNum === 1) {
        carItems.value = res.data.list.data;
        triggered.value = false;
      } else if (res.data.list.current_page <= res.data.list.last_page) {
        carItems.value.push(...res.data.list.data);
      }
    }
  });
}

function fetchSpaData() {
  const payload: any = {
    page: pagination.pageNum,
    pageSize: pagination.pageSize
  };
  if (current.value == 1) {
    payload['orderStatus'] = OrderStatus.WAIT_PAY;
  } else if (current.value == 2) {
    payload['orderStatus'] = OrderStatus.ORDER_SUCCESS;
  } else if (current.value == 3) {
    payload['orderStatus'] = OrderStatus.CANCEL;
  }
  getSpaOrders(payload).then((res) => {
    if (!initialized.value) {
      initialized.value = true;
    }
    totalCount.value = res.total;
    if (pagination.pageNum === 1) {
      spaItems.value = res.data;
      triggered.value = false;
    } else if (res.current_page <= res.last_page) {
      spaItems.value.push(...res.data);
    }
  });
}

function fetchData() {
  if (currentTab.value == 'checkout') {
    fetchHotelData();
  } else if (currentTab.value == 'dining') {
    fetchRestaurantData();
  } else if (currentTab.value == 'car') {
    fetchCarData();
  } else {
    fetchSpaData();
  }
}

watch(current, () => {
  scrollTop.value = oldScrollTop.value;
  setTimeout(() => {
    scrollTop.value = 0;
  }, 100);
  pagination.pageNum = 1;
  fetchData();
});
watch(() => pagination.pageNum, fetchData);
watch(currentTab, () => {
  scrollTop.value = oldScrollTop.value;
  setTimeout(() => {
    scrollTop.value = 0;
  }, 100);
  if (pagination.pageNum == 1) {
    fetchData();
  } else {
    pagination.pageNum = 1;
  }
});

const initialized = ref(false);

const changeOrderStatus = (status: string, index: number) => {
  if (currentTab.value == 'checkout') {
    items.value[index].orderStatus = status;
  } else if (currentTab.value == 'car') {
    carItems.value[index].actual_order_status = status;
  } else if (currentTab.value == 'dining') {
    restaurantItems.value[index].actual_order_status = status;
  } else if (currentTab.value == 'spa') {
    spaItems.value[index].actual_order_status = status;
  }
};

onLoad(async (options) => {
  uni.getSystemInfo({
    success: (res) => {
      statusBarH.value = res.statusBarHeight || 0;
    }
  });
  currentTab.value = options?.tab ? options?.tab : 'checkout';
});

onShow(() => fetchData());

function handleCancel(orderSn: string) {
  cancelUnpaidOrder(orderSn).then(() => {
    fetchData();
  });
}

function handleCarOrderCancel(orderSn: string) {
  cancelOrder(orderSn, true).then(() => {
    fetchData();
  });
}

function handleRestaurantOrderCancel(orderSn: string) {
  cancelRestaurantOrder(orderSn).then(() => {
    fetchData();
  });
}

function handleSpaOrderCancel(orderSn: string) {
  cancelSpaOrder(orderSn).then(() => {
    fetchData();
  });
}

function handleRefresh() {
  triggered.value = true;
  if (pagination.pageNum == 1) {
    fetchData();
  } else {
    pagination.pageNum = 1;
  }
}

function handleLoadMore() {
  if (items.value.length >= totalCount.value) {
    return;
  }
  pagination.pageNum += 1;
}

function navigateToLogin() {
  if (!authStore.isLoggedIn) {
    uni.navigateTo({
      url: '/pages/auth/login'
    });
  }
}

defineExpose({
  changeOrderStatus
});
</script>

<template>
  <uni-nav-bar
    v-if="isWechat()"
    :border="false"
    :title="t('LOKey_orderMy')"
    fixed
    left-icon="left"
    status-bar
    @click-left="router.back"
  />

  <OrderTabs v-model="current" />
  <OrderType v-model="currentTab" />

  <scroll-view
    :refresher-triggered="triggered"
    :scrollTop="scrollTop"
    :style="{ height: 'calc(100vh - 44px - 220rpx - ' + statusBarH + 'px)' }"
    refresher-enabled
    scroll-y
    @refresherrefresh="handleRefresh"
    @scroll="scrollStart"
    @scrolltolower="handleLoadMore"
  >
    <uv-list
      v-if="totalCount > 0"
      :custom-style="{
        padding: '10rpx 0rpx',
        backgroundColor: '#f4f4f4'
      }"
    >
      <template v-if="currentTab == 'checkout'">
        <uv-list-item
          v-for="(item, index) in items"
          :key="item.orderSn"
          :custom-style="{
            padding: '10rpx 24rpx',
            backgroundColor: '#f4f4f4'
          }"
        >
          <order-card
            :address="item.Address"
            :check-in-date="item.checkInDate"
            :check-out-date="item.checkOutDate"
            :countdown="item.countdown"
            :created-at="item.createTime"
            :days="item.days"
            :index="index"
            :name="item.propertyName"
            :order-amount="item.order_amount"
            :order-sn="item.orderSn"
            :payment-amount="item.thirePayAmount"
            :person="item.adult_count + item.child_count"
            :refund-status="item.refundStatus"
            :room-num="item.roomNum"
            :status="item.orderStatus"
            :type="1"
            @cancel="handleCancel"
          />
        </uv-list-item>
      </template>

      <template v-else-if="currentTab == 'car'">
        <uv-list-item
          v-for="(item, index) in carItems"
          :key="item.order_sn"
          :custom-style="{
            padding: '10rpx 24rpx',
            backgroundColor: '#f4f4f4'
          }"
        >
          <car-order-card
            :bookDate="item.book_date"
            :bookTime="item.book_time"
            :carTypeName="item.car_type_name"
            :countdown="item.count_down"
            :createdAt="item.created_at"
            :endAddress="item.end_address"
            :index="index"
            :actualAmount="item.actual_amount"
            :orderAmount="item.order_amount"
            :orderSn="item.order_sn"
            :orderType="item.order_type"
            :serviceType="item.service_type"
            :startAddress="item.start_address"
            :status="item.actual_order_status"
            @cancel="handleCarOrderCancel"
          />
        </uv-list-item>
      </template>

      <template v-else-if="currentTab == 'dining'">
        <uv-list-item
          v-for="(item, index) in restaurantItems"
          :key="item.order_sn"
          :custom-style="{
            padding: '10rpx 24rpx',
            backgroundColor: '#f4f4f4'
          }"
        >
          <restaurant-order-card
            :address="item.restaurant.full_address"
            :booking-count="item.booking_count"
            :booking-date="item.book_date"
            :booking-time="item.book_time"
            :countdown="item.count_down"
            :index="index"
            :name="item.restaurant.name"
            :actual-amount="item.actual_amount"
            :order-amount="item.order_amount"
            :order-sn="item.order_sn"
            :status="item.actual_order_status"
            @cancel="handleRestaurantOrderCancel"
          />
        </uv-list-item>
      </template>

      <template v-else-if="currentTab == 'spa'">
        <uv-list-item
          v-for="(item, index) in spaItems"
          :key="item.order_sn"
          :custom-style="{
            padding: '10rpx 24rpx',
            backgroundColor: '#f4f4f4'
          }"
        >
          <spa-order-card
            :booking-count="item.goods_num"
            :booking-date="item.book_date"
            :booking-time="item.book_time"
            :countdown="item.count_down"
            :index="index"
            :name="item.service_name"
            :booking-type="item.service_type"
            :actual-amount="item.actual_amount"
            :order-amount="item.order_amount"
            :order-sn="item.order_sn"
            :status="item.actual_order_status"
            @cancel="handleSpaOrderCancel"
          />
        </uv-list-item>
      </template>
    </uv-list>

    <view v-else class="flex flex-col flex-center pt-4">
      <image
        src="https://apt11-1251002327.cos.ap-tokyo.myqcloud.com/miniapp/car/icon_car_order_nolist.png"
        style="width: 556rpx; height: 556rpx"
      />
      <view v-if="authStore.isLoggedIn" class="text-base text-fourth">
        {{ t('StaffNoRelatedOrders') }}
      </view>
      <view v-else class="flex flex-center py-2 px-4 rounded bg-green" @click="navigateToLogin">
        <text class="text-sm text-white">{{ t('SignIn') }}</text>
      </view>
    </view>

    <apt-safe-area />
  </scroll-view>
</template>
